#!/usr/bin/env python

# Entertainer backend - This is a server side of the Entertainer media center.
# Copyright (C) 2007 Lauri Taimila
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2007, Lauri Taimila"
__author__ = "Lauri Taimila <lauri@taimila.com>"
__version__= "0.1"

import gobject
import os
import sys
from backend.backend_server import BackendServer
import dl

#Use this to daemonize a program/process
def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
    # Perform the first fork
    try:
        pid = os.fork()
        if pid  > 0:
            sys.exit(0) # Exit first parent
    except OSError, e:
        sys.stderr.write("First fork failed: (%d) %s\n" % (e.errno, e.strerror))
        sys.exit(1)
    # Decouple from parent environment 
    os.chdir("/")
    os.umask(0)
    os.setsid()		
    # Perform the second fork
    try:
        pid = os.fork()
        if pid  > 0:
            sys.exit(0) # Exit second parent
    except OSError, e:
        sys.stderr.write("Second fork failed: (%d) %s\n" % (e.errno, e.strerror))
        sys.exit(1)	
    # The process is now daemonize, appart from scaring children it'll now run as a daemon
    for f in sys.stdout, sys.stderr: f.flush()
    si = file(stdin, 'r')
    so = file(stdout, 'a+')
    se = file(stderr, 'a+')
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())		
    os.dup2(se.fileno(), sys.stderr.fileno())


if __name__ == "__main__":
    if len(sys.argv) > 1 and (sys.argv[1] == "--help" or sys.argv[1] == "-h"):
        print "Entertainer backend " + str(__version__) + ", Copyright (c) " + str(__copyright__)
        print ""
        print "Usage:"
        print "    --help               - This help listing"
        print "    --foreground         - Run backend as foreground process"
        sys.exit(0)
    
    if len(sys.argv) > 1 and sys.argv[1] == "--foreground":
        backend = BackendServer()
    else:
        print "Entertainer backend starting..."
        libc = dl.open('/lib/libc.so.6')
        libc.call('prctl', 15, 'EntertainerBE', 0, 0, 0)
        daemonize()
        backend = BackendServer()

